package org.example.zuoye.api;

import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.Getter;
import org.apache.coyote.Response;
import org.example.zuoye.entity.Admin;
import org.example.zuoye.entity.Result;
import org.example.zuoye.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

import static com.wf.captcha.utils.CaptchaUtil.setHeader;

/**
 * @Author xinchen
 * @Date: 2024/08/10/ 16:04
 * @Description 控制层管理员
 */
@RestController
@RequestMapping(value = "/api/v1/admin")
public class AdminApi {

    @Autowired
    private AdminService adminService;

    /**
     * 条件 + 分页查询
     */
    @GetMapping
    public Result getAll(@RequestParam(defaultValue = "1") Integer page,
                         @RequestParam(defaultValue = "10") Integer limit, Admin admin) {

        return Result.success(adminService.searchByPage(page, limit, admin));
    }

    /**
     * add
     */
    @PostMapping
    public Result add(@RequestBody Admin admin) {
        try {
            adminService.add(admin);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * remove
     */
    @DeleteMapping
    public Result remove(@RequestBody Integer[] ids) {
        try {
            adminService.remove(ids);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }
    /**
     * update
     */
    @PutMapping
    public Result edit(@RequestBody Admin admin){
        try {
            adminService.edit(admin);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * 生成验证码
     */
    @GetMapping("/captcha")
    public void captcha(HttpServletResponse resp, HttpSession session) throws IOException {
        // 生成验证码
        SpecCaptcha cap = new SpecCaptcha(130, 48, 4);

        // 设置响应头
        resp.setContentType("image/gif");
        resp.setHeader("Pragma", "No-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 0L);

        // 将答案存储到session中
        session.setAttribute("captcha", cap.text().toLowerCase());
        cap.out(resp.getOutputStream());
    }
    /**
     * 根据用户名进行查询数据
     */
    @GetMapping("/username/{username}")
    public Result findByUsername(@PathVariable String username) {
        Admin admin = adminService.findByUsername(username);
        if (admin != null) {
            return Result.success(admin);
        } else {
            return Result.error("用户不存在");
        }
    }
}



